﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TI_BAL;
using SecuritySystem.Reports.Datasets;


namespace SecuritySystem
{
    public partial class SaleTransaction : Form
    {
        int CASH_ACCOUNT_DB_ID = 3;
        int ACCOUNTS_RECIEVABLE_ACCOUNT_DB_ID = 4;
        TIEntities dbContext;
        List<ProductType> productTypeList;
        List<ProductSubType> productSubTypeList;
        int INVOICE_ID = -1;
        public Form parentWindow;

        //public DataGridViewRow selectedRecord = null;

        public SaleTransaction()
        {
            InitializeComponent();
            dbContext = new TIEntities();
            FillTypeCombo();
            FillCustomerCombo();
        }

        private void FillTypeCombo()
        {
            productTypeList = (from pt in dbContext.ProductTypes select pt).Distinct().ToList();
            if (productTypeList != null)
            {
                BindDataWithTypeCombo(productTypeList);
            }
            else
            {
                productTypeList = new List<ProductType>();
            }

        }

        private void BindDataWithTypeCombo(List<ProductType> productTypeList)
        {

            this.comboBoxProductType.DataSource = null;
            comboBoxProductType.DisplayMember = "Name";
            comboBoxProductType.ValueMember = "ID";
            comboBoxProductType.DataSource = productTypeList;
            comboBoxProductType.Refresh();
        }


        private void FillCustomerCombo()
        {

            List<Customer> CustomerList = (from pt in dbContext.Customers select pt).ToList<Customer>();
            if (CustomerList != null)
            {
                BindDataWithCustomerCombo(CustomerList);
            }
            else
            {
                CustomerList = new List<Customer>();
            }

        }

        private void BindDataWithCustomerCombo(List<Customer> CustomerList)
        {

            this.comboBoxCustomer.DataSource = null;
            comboBoxCustomer.DisplayMember = "CustomerCompanyName";
            comboBoxCustomer.ValueMember = "ID";
            comboBoxCustomer.DataSource = CustomerList;
            comboBoxCustomer.Refresh();
        }


        private void clearFields() {
            this.comboBoxCustomer.SelectedIndex = 0;
            this.comboBoxProductSubType.SelectedIndex = 0;
            this.comboBoxProductType.SelectedIndex = 0;
            this.comboBoxSize.SelectedIndex = 0;

            this.textBoxQuantity.Text = "";
            this.textPrice.Text = "";

            this.dataGridViewSale.Rows.Clear();
            this.radioButtonCash.Checked = true;

        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            try
            {
                List<SalesTransaction> productSubTypeList = (from pt in dbContext.SalesTransactions select pt).ToList<SalesTransaction>();
                int invoiceId = 3000 + productSubTypeList.Count;
                INVOICE_ID = invoiceId;

                foreach (DataGridViewRow rowWalker in this.dataGridViewSale.Rows)
                {
                    int accountId = 0;
                    Journal journal = new Journal();
                    int productTypeID = int.Parse(rowWalker.Cells["ProductType"].Tag.ToString());
                    int productSubTypeID = int.Parse(rowWalker.Cells["SubType"].Tag.ToString());
                    int sizeID = int.Parse(rowWalker.Cells["Size"].Tag.ToString());

                    if (rowWalker.Cells["Transaction"].Value.ToString() == "Cash")
                    {
                        accountId = CASH_ACCOUNT_DB_ID;
                    }
                    else {
                        accountId = ACCOUNTS_RECIEVABLE_ACCOUNT_DB_ID;
                    }
                    
                    int customerID = int.Parse(rowWalker.Cells["Customer"].Tag.ToString());

                    Account account = (from acc in dbContext.Accounts where acc.Account_ID == accountId select acc).FirstOrDefault();
                    journal.Account = account;
                    journal.Journal_Amount = Convert.ToDouble(rowWalker.Cells["TotalPrice"].Value.ToString());
                    journal.Journal_Date = DateTime.Parse(rowWalker.Cells["Date"].Value.ToString());
                    
                    journal.Product_Type = rowWalker.Cells["ProductType"].Value.ToString();
                    journal.Sub_Type = rowWalker.Cells["SubType"].Value.ToString();
                    journal.Product_Size = rowWalker.Cells["Size"].Value.ToString();
                    journal.Quantity = Convert.ToInt32(rowWalker.Cells["Quantity"].Value.ToString());
                    journal.Per_Item_Price = Decimal.Round((Convert.ToDecimal(rowWalker.Cells["TotalPrice"].Value.ToString()) / Convert.ToDecimal(rowWalker.Cells["Quantity"].Value.ToString())), 2);

                    if (this.checkBoxSalesReturn.Checked == false)
                    {
                        journal.TransactionType = "D";
                        journal.Journal_Description = "Sales transaction";

                        if (rowWalker.Cells["Transaction"].Value.ToString() != "Cash")
                        {
                            journal.Customer = (from acc in dbContext.Customers where acc.ID == customerID select acc).FirstOrDefault();                            
                        }

                        journal.Debit_Amount = journal.Journal_Amount;
                        journal.Credit_Amount = 0;
                    }
                    else {
                        journal.TransactionType = "C";
                        journal.Journal_Description = "Sales Return";

                        if (rowWalker.Cells["Transaction"].Value.ToString() != "Cash")
                        {
                            journal.Customer = (from acc in dbContext.Customers where acc.ID == customerID select acc).FirstOrDefault();                            
                        }

                        journal.Debit_Amount = 0;
                        journal.Credit_Amount = journal.Journal_Amount;

                        
                            try
                            {
                                Inventory inv = new Inventory();

                                inv.ItemCode = "Sales Return";
                                inv.ItemName = "Sales Return";
                                inv.Description = "Sales Return";
                                inv.Quantity = int.Parse(journal.Quantity.ToString());
                                inv.Price = decimal.Parse(journal.Per_Item_Price.ToString());


                                inv.PurchaseDate = DateTime.Now;
                                inv.SupplierID = 3;;
                                inv.ProductTypeID = productTypeID;
                                inv.ProductSubTypeID = productSubTypeID;
                                inv.SizeID = sizeID;

                                dbContext.AddToInventories(inv);
                                

                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Some Error Occured");
                            }
                        
                    }
                    

                    dbContext.AddToJournals(journal);

                    SalesTransaction sale = new SalesTransaction();

                    
                    

                    sale.Customer = (from acc in dbContext.Customers where acc.ID == customerID select acc).FirstOrDefault();
                    sale.DATE = this.dateTimePickerSaleDate.Value;
                    sale.INVOICE_ID = invoiceId;
                    try
                    {
                        sale.PER_UNIT_PRICE = Decimal.Round((Convert.ToDecimal(rowWalker.Cells["TotalPrice"].Value.ToString()) / Convert.ToDecimal(rowWalker.Cells["Quantity"].Value.ToString())),2);
                    }
                    catch {
                        MessageBox.Show("Invalid price or quantity in some order Item");
                        return;
                    }


                    sale.ProductType = (from acc in dbContext.ProductTypes where acc.ID == productTypeID select acc).FirstOrDefault();
                    sale.ProductSubType = (from acc in dbContext.ProductSubTypes where acc.ID == productSubTypeID select acc).FirstOrDefault();
                    sale.ProductSize = (from acc in dbContext.ProductSizes where acc.ID == sizeID select acc).FirstOrDefault();

                    sale.Account = (from acc in dbContext.Accounts where acc.Account_ID == accountId select acc).FirstOrDefault();

                    sale.QUANITY = Convert.ToDecimal(rowWalker.Cells["Quantity"].Value.ToString());
                    dbContext.AddToSalesTransactions(sale);
                    
                    dbContext.SaveChanges();

                    
                    
                }
                if (checkBoxSalesReturn.Checked == false)
                {
                    ReportForm reportForm = new ReportForm();
                    reportForm.ReportType = "InvoiceReport";
                    reportForm.InvoiceId = INVOICE_ID;
                    reportForm.MdiParent = parentWindow;
                    reportForm.Show();

                    reportForm.WindowState = FormWindowState.Minimized;
                    reportForm.WindowState = FormWindowState.Maximized;
                }
                

                clearFields();
            }
            catch {
                MessageBox.Show("There was some error in saving transaction, please see if there some error in data");
                //clearFields();
            }
             
            
        }

        private void SaleTransaction_Load(object sender, EventArgs e)
        {
            this.dateTimePickerSaleDate.Value = DateTime.Now;                    
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void comboBoxProductType_SelectedIndexChanged(object sender, EventArgs e)
        {
            FillSubTypeCombo();
            FillSizeCombo();
        }

        private void FillSubTypeCombo()
        {
            int selectedTypeId = Convert.ToInt32(this.comboBoxProductType.SelectedValue.ToString());
            List<ProductSubType> productSubTypeList = (from pt in dbContext.ProductSubTypes where pt.ProductTypeID == selectedTypeId select pt).ToList<ProductSubType>();
            if (productSubTypeList != null)
            {
                BindDataWithSubTypeCombo(productSubTypeList);
            }
            else
            {
                productSubTypeList = new List<ProductSubType>();
            }
        }

        private void BindDataWithSubTypeCombo(List<ProductSubType> productSubTypeList)
        {

            this.comboBoxProductSubType.DataSource = null;
            comboBoxProductSubType.DisplayMember = "Name";
            comboBoxProductSubType.ValueMember = "ID";
            comboBoxProductSubType.DataSource = productSubTypeList;
            comboBoxProductSubType.Refresh();
        }

        private void comboBoxProductSubType_SelectedIndexChanged(object sender, EventArgs e)
        {

        }


        private void FillSizeCombo()
        {
            int selectedTypeId = Convert.ToInt32(this.comboBoxProductType.SelectedValue.ToString());
            List<ProductSize> productSizeList = (from pt in dbContext.ProductSizes where pt.TypeID == selectedTypeId select pt).ToList<ProductSize>();
            if (productSizeList != null)
            {
                BindDataWithSizeCombo(productSizeList);
            }
            else
            {
                productSizeList = new List<ProductSize>();
            }
        }

        private void BindDataWithSizeCombo(List<ProductSize> productSizeList)
        {

            this.comboBoxSize.DataSource = null;
            comboBoxSize.DisplayMember = "Name";
            comboBoxSize.ValueMember = "ID";
            comboBoxSize.DataSource = productSizeList;
            comboBoxSize.Refresh();
        }

        private void buttonAddOrder_Click(object sender, EventArgs e)
        {
            try {

                if (this.comboBoxCustomer.SelectedIndex == -1)
                {
                    MessageBox.Show("Customer does not exist, please select the correct customer");
                    return;
                }

                if (this.comboBoxProductType.SelectedIndex == -1)
                {
                    MessageBox.Show("Product does not exist, please select the correct product");
                    return;
                }

            if (this.textPrice.Text.Trim() == "" || this.textBoxQuantity.Text.Trim() == "")
            {
                MessageBox.Show("Price and quantity are Mendatory fields");
                return;
            }

            DataGridViewRow rowToAdd = new DataGridViewRow();
            int index = this.dataGridViewSale.Rows.Add(rowToAdd);

            this.dataGridViewSale.Rows[index].Cells["Customer"].Value = this.comboBoxCustomer.Text.ToString();
            this.dataGridViewSale.Rows[index].Cells["Customer"].Tag = this.comboBoxCustomer.SelectedValue.ToString();
            this.dataGridViewSale.Rows[index].Cells["ProductType"].Value = this.comboBoxProductType.Text.ToString();
            this.dataGridViewSale.Rows[index].Cells["ProductType"].Tag = this.comboBoxProductType.SelectedValue.ToString();
            this.dataGridViewSale.Rows[index].Cells["SubType"].Value = this.comboBoxProductSubType.Text.ToString();
            this.dataGridViewSale.Rows[index].Cells["SubType"].Tag = this.comboBoxProductSubType.SelectedValue.ToString();
            this.dataGridViewSale.Rows[index].Cells["Size"].Value = this.comboBoxSize.Text.ToString();
            this.dataGridViewSale.Rows[index].Cells["Size"].Tag = this.comboBoxSize.SelectedValue.ToString();

            this.dataGridViewSale.Rows[index].Cells["Quantity"].Value = this.textBoxQuantity.Text;
            double totalPrice =  double.Parse(this.textPrice.Text) * double.Parse(this.textBoxQuantity.Text);

            if (this.textBoxPercentage.Text == "")
            {
                this.textBoxPercentage.Text = "0";
            }

            double discount = double.Parse(this.textBoxPercentage.Text);

            if (discount != 0)
            {
                this.dataGridViewSale.Rows[index].Cells["TotalPrice"].Value = (totalPrice - (discount * totalPrice / 100)).ToString();
            }
            else 
            {
                this.dataGridViewSale.Rows[index].Cells["TotalPrice"].Value = totalPrice.ToString();
            }

            this.dataGridViewSale.Rows[index].Cells["Date"].Value = this.dateTimePickerSaleDate.Value;

            if (this.radioButtonCash.Checked == true)
            {
                this.dataGridViewSale.Rows[index].Cells["Transaction"].Value = "Cash";
            }
            else
            {
                this.dataGridViewSale.Rows[index].Cells["Transaction"].Value = "Credit";
            }


            }catch{
                MessageBox.Show("Error in transaction");
            }

            //rowToAdd.Cells['Customer'] = ;
            //rowToAdd.Cells['ProductType'] = ;
            //rowToAdd.Cells['SubType'] = ;
            //rowToAdd.Cells['Size'] = ;
            //rowToAdd.Cells['Quantity'] = ;
            //rowToAdd.Cells['TotalPrice'] = ;
            //rowToAdd.Cells['Date'] = ;
            


        }

        private void groupBox2_Enter(object sender, EventArgs e)
        {

        }

        private void label1Customer_Click(object sender, EventArgs e)
        {

        }

        private void label10_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                this.dataGridViewSale.Rows.Remove(this.dataGridViewSale.SelectedRows[0]);
            }
            catch { }
            //this.dataGridViewSale.SelectedRows[0].Index
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void buttonShowInvoice_Click(object sender, EventArgs e)
        {
            ReportForm reportForm = new ReportForm();
            reportForm.ReportType = "InvoiceReport";
            reportForm.InvoiceId = INVOICE_ID;
            reportForm.MdiParent = parentWindow;
            reportForm.Show();

            reportForm.WindowState = FormWindowState.Minimized;
            reportForm.WindowState = FormWindowState.Maximized;
            
        }

    }
}
